<?php
class Seo_Plugin_Seo extends Zend_Controller_Plugin_Abstract {

	
	public function postDispatch(Zend_Controller_Request_Abstract $request) {
		$layout = Zend_Layout::getMvcInstance ();
		$view = $layout->getView ();
		
		if(Zend_Registry::isRegistered('cid')){
			$page_id=Zend_Registry::get('cid');
		}else{
			$url=$_SERVER['REQUEST_URI'];
			$url=preg_replace('/\\/?\\?.*/', '', $url);
			$url=preg_replace('/\\/$/', '', $url);
			$url .= '/'; 
			$page_id = $url;
		}
		
		$page_id=md5($page_id);
		$data =  Zen_Settings::get('seo', 'pages');
		
		if(isset($data[$page_id])){
			$view->title = ($data[$page_id]['title']) ? $data[$page_id] ['title'] : $view->title;
			$view->keywords = ($data[$page_id]['keywords']) ? $data[$page_id] ['keywords'] : $view->keywords;
			$view->description = ($data[$page_id]['description']) ? $data[$page_id] ['description'] : $view->description;
		}
		else{
			$data= Zen_Settings::get('seo', 'settings');
			if($data){
				if (! $view->title) {
					$view->title = $data ['title'];
				}
				if (! $view->keywords) {
					$view->keywords = $data ['keywords'];
				}
				if (! $view->description) {
					$view->description = $data ['description'];
				}
				if(isset($data['head'])&&$data['head']!=""){
					$view->head .= $data ['head'];
				}
			}
		}
	}

	public function dispatchLoopShutdown() {
		$route = Zend_Controller_Front::getInstance ()->getRouter ()->getCurrentRouteName ();
		if (($route != 'admin') && ($route != 'backend')) {
			$response = $this->getResponse ();
			
			$body = $response->getBody ();
			$matches = array ();
			$reg_exp = "/<\\s*a\\s+[^<>]*href\\s*=\\s*[\"|']http:.*[\"|'].*<\\/a>/isU";
			preg_match_all ( $reg_exp, $body, $matches );
			$matches = $matches [0];
			if (count ( $matches )) {
				foreach ( $matches as $key => $match ) {
					$int_matches = array ();
					preg_match ( "/.*(\"|')\\s*follow\\s*(\"|').*/", $match, $int_matches );
					if (count ( $int_matches )) {
						continue;
					}
					$match = preg_replace ( "/>/", " rel='nofollow'>", $match, 1 );
					$body = str_replace ( $matches [$key], '<!--noindex-->' . $match . '<!--/noindex-->', $body );
				}
			}


			//Добавление слешей в конце всех ссылок
			$links = array ();
			//Ищем все ссылки
			$reg_exp = "/<\\s*a\\s+[^<>]*href\\s*=\\s*[\"|']([^\\?].*)[\"|'].*<\\/a>/isU";
			preg_match_all ( $reg_exp, $body, $links );

			foreach ( $links [1] as $link ) {

				$link = trim ( $link );

				if (! preg_match ( '/[#\.]/', $link )&&($link!="")&&($link!="/")&&(!preg_match('/[\'\"]/', $link)))
				if (! preg_match ( '/\/$/', $link )) {
					$preg = '/(' . str_replace ( '/', '\/', $link ) . ')\s*(["\'])/i';
					$body = preg_replace ( $preg, '$1/$2', $body );
				}
					
			}
			$seo_params=Zen_Settings::get('seo', 'settings');
			if(($seo_params['codes']!="")&&(APPLICATION_ENV=="production")){
				$body=preg_replace('/\<\\/body\>/ui', $seo_params['codes']."</body>", $body);
			}
			$response->setBody ( $body );
		}
	}

}